package com.nuist.dao;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

// 操作数据库的公共类
public class BaseDao {

    private static final String driver;
    private static final String url;
    private static final String user;
    private static final String password;

    // 类加载时候初始化
    static {
        // 通过类加载器进行文件加载
        Properties prop = new Properties();
        InputStream input = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            prop.load(input);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        driver = prop.getProperty("driverClass");
        url = prop.getProperty("url");
        user = prop.getProperty("user");
        password = prop.getProperty("password");
    }

    // 编写数据库的连接
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Connection conn = null;
        Class.forName(driver);
        System.out.println("加载数据库成功！");
        conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    // 查询数据库的公共操作
    public static ResultSet execute(Connection connection, PreparedStatement pstm, ResultSet rs, String sql, Object[] params) {
        try {
            pstm = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            rs = pstm.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }

    // 更新数据库的公共操作
    public static int execute(Connection connection, PreparedStatement pstm, String sql, Object[] params) {
        int updateRows = 0;
        try {
            pstm = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
            updateRows = pstm.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return updateRows;
    }

    // 释放数据库连接
    public static void closeConnection(Connection con, Statement stmt, ResultSet rs){
        try{
            if(rs != null){
                rs.close();
            }
            if(stmt != null){
                stmt.close();
            }
            if (con != null){
                con.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void closeConnection(Connection con, Statement stmt){
        closeConnection(con, stmt, null);
    }

}
